package tech.aistar.service.impl.like;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tech.aistar.mapper.like.PraiseMapper;
import tech.aistar.service.like.IPraiseService;

import java.util.Set;

/**
 * Created by lenovo on 2019/10/17.
 */
@Service
@Transactional
public class PraiseServiceImpl implements IPraiseService {

    @Autowired
    private PraiseMapper praiseMapper;
    //导入redis
    @Autowired
    private RedisTemplate redisTemplate;

    //保存点赞信息
    @Override
    public String addPraise(Integer noteId, Integer userId) {

        System.err.println("impl////////////////");
        String idone = String.valueOf(noteId);
        String idtwo = String.valueOf(userId);
        long InsertState = redisTemplate.opsForSet().add(idone, idtwo);
        redisTemplate.opsForValue().setIfAbsent("note" + idone, 1);
        if ((int) InsertState == 1) {
//          redisTemplate.opsForValue().increment("note" + idone, 1);
            redisTemplate.opsForValue().getAndSet("note" + idone, 1);
            Object o = redisTemplate.opsForValue().get("note" + idone);
            System.out.println(o);

            return o.toString();
        } else {
//            return "no";
            redisTemplate.opsForValue().getAndSet("note" + idone, 0);
            Object o = redisTemplate.opsForValue().get("note" + idone);
            System.out.println(o);
            return o.toString();
        }
    }

    /**
     * 将redis中保存的值取出,保存在mysql中
     */
    @Override
    public void deleteRedis() {
        //获取每个人的点赞数
        Set<String> set = redisTemplate.keys("note*");

        for (String key : set){
            String keys = key.split("note")[1];
            Integer num = (Integer) redisTemplate.opsForValue().get(key);
            Integer noteId = Integer.valueOf(keys);
            praiseMapper.updatePraise(num,noteId);
            praiseMapper.updataNotesSuppById(num,noteId);
            redisTemplate.delete(keys);
        }
        redisTemplate.delete(set);
    }
}
